package cn.qiyu5522.service.impl;

import cn.qiyu5522.domain.entity.RoleMenu;
import cn.qiyu5522.mapper.RoleMenuMapper;
import cn.qiyu5522.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色和菜单关联表 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2024-04-22
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Override
    public List<Long> selectMenuIdsByRoleIds(List<Long> roleId) {
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RoleMenu::getRoleId, roleId);
        List<RoleMenu> roleMenus = list(queryWrapper);
        List<Long> menuIds = roleMenus.stream().map(rm -> rm.getMenuId()).collect(Collectors.toList());
        return menuIds;
    }

    @Override
    public void saveBatchByRoleIdMenuIds(Long roleId, List<Long> menuIds) {
        List<RoleMenu> roleMenus = menuIds.stream().map(menuId -> new RoleMenu(roleId, menuId)).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId, roleId);
        // 先删除
        remove(lambdaQueryWrapper);
        // 在添加
        saveBatch(roleMenus);
    }
}
